#include "member.h"
#include<QJsonObject>
#include<QJsonArray>
#include<QJsonDocument>

#include<QDateTime>




MemberManage::MemberManage(){}

MemberManage::~MemberManage(){}

bool MemberManage::initFromJsonString(const std::string &json)
{
    members.clear();
    QJsonDocument jd = QJsonDocument::fromJson(QByteArray::fromStdString(json));
    if (jd.isArray()){
        QJsonArray ja = jd.array();
        for(int i=0;i<ja.size();i++){
            QJsonObject jo = ja.at(i).toObject();

            bool enable;
            if (jo.value("enable")=="T"){
                enable = true;
            }else if (jo.value("enable")=="F"){
                enable = false;
            }else{
                return false;
            }
            members.push_back(Member{jo.value("id").toString().toStdString(),jo.value("name").toString().toStdString(),enable});
        }

    }
    return true;
}


bool MemberManage::addMember(const std::string &name){
    Member m{getNewId(),name,true};
    members.push_back(m);
}

bool MemberManage::editMember(const int &index, const std::string &id, const std::string &name){
    if(members.at(index).id==id){
        members.at(index).name = name;
        return true;
    }else{
        return false;
    }

}
std::string MemberManage::toJson(){
    QJsonArray jsonArr;
    for(int i=0;i<members.size();i++){
        QJsonObject l;
        l.insert("enable",QString::fromStdString(members.at(i).enable?"T":"F"));
        l.insert("name",QString::fromStdString(members.at(i).name));
        l.insert("id",QString::fromStdString(members.at(i).id));
        jsonArr.append(l);
    }
    QJsonDocument jd(jsonArr);
    QString s;
    s.prepend(jd.toJson());
    std::cout<<s.toStdString()<<std::endl;
    return s.toStdString();
}

std::string MemberManage::getNewId(){
    return QDateTime::currentDateTime().toString("yyyyMMddhhmmss").toStdString();
}

Member MemberManage::getMember(const int &i){
    return members.at(i);
}

int MemberManage::count(){
    return members.size();
}

bool MemberManage::deleteMember(){
    //TODO  implement it later
}




